;(function (undefined) {
    var _global;

    // var template = document.getElementById(tempId);
    if (typeof template === "function") {
        template.defaults.imports.getCover = function (pic) {
            // "201801091356472785.jpg∮201801091356477890.jpg"
            if (pic.indexOf('∮') !== -1) {
                var arr = pic.split("∮");
                return CONFIG.IMAGE_RESOURCES_ADDRESS + arr[0];
            } else {
                return CONFIG.IMAGE_RESOURCES_ADDRESS + pic;
            }
        };
        template.defaults.imports.DateFormat = function (date, format) {
            return new Date(date.replace(/-/g, '/')).Format(format);
        };
        template.defaults.imports.JSONFormat = function (jsonString) {
            if (typeof JSON !== 'undefined') {
                return JSON.parse(jsonString);
            } else {
                return eval(jsonString)
            }
        };
        template.defaults.imports.subStr = function (str, num) {
            if (num > str.length) {
                return str;
            } else {
                return str.substr(0, num) + '...'
            }
        };

        template.defaults.imports.getListUrl = function (genre) {
            var detailObj = {
                text: 'text.html',//纯文
                imgText: 'imgText.html',//图文
                video: 'videoDetail.html',//视频
                multiImg: 'imgDetail.html',//多图
                richText: 'detail.html',//富文本
                audio: ''//音频
            };
            var url = '';
            genre = parseInt(genre);
            switch (genre) {
                case 1:
                    url = detailObj.text;
                    break;
                case 2:
                    url = detailObj.imgText;
                    break;
                case 3:
                    url = detailObj.video;
                    break;
                case 4:
                    url = detailObj.multiImg;
                    break;
                case 5:
                    url = detailObj.richText;
                    break;
                case 6:
                    url = detailObj.audio;
                    break;
                default:
                    break;
            }
            return url;
        };
    }

    function List(options) {
        var defaults = {
            action: '',
            params: {
                menuId: '',
                stairColumnId: '',
                pageIndex: 0,
                pageSize: 10
            },
            col: 1,
            offsetTop: 0,
            offsetLeft: 0,
            tempId: 'listTemp',
            //用于生成唯一ID
            itemClassName: 'list-item',
            //如果根据className生成的ID重复则需添加前缀
            idPrefix: '',
            fullIdPrefix: '',
            lastElemIndex: 0,
            lastDirection: '',
            pageControl: false,
            positionControl: false,
            keyPress: false,
            keyPressControl: false,
            pageControlGoLeft: '',
            pageControlGoTop: '',
            pageControlGoRight: '',
            pageControlGoBottom: '',
            direction: 'vertical',//horizontal水平排列,vertical竖直排列
            totalPage: 1,
            currentPage: 1,
            prevPage: 1,
            pageControlId: 'page',
            itemHeight: 0,
            itemWidth: 0,
            callback: function () {
            }
        };
        this.firstView=true;
        this.nodeCache = {};
        this.def = extend(defaults, options, true);
        this.def.callback = options.callback;
        return this;
    }

    List.prototype.template = function (tempId) {
        this.def.tempId = tempId;
        return this;
    };
    List.prototype.setParams = function (params) {
        this.def.params = extend(this.def.params, params);
        return this;
    };
    List.prototype.setOptions = function (key, value) {
        this.def[key] = value;
        return this;
    };
    List.prototype.setColNum = function (num) {
        this.def.col = num;
        return this;
    };
    List.prototype.getData = function (mock) {
        // API.getDataList()
        var templateNode = document.getElementById(this.def.tempId);
        this.clearData();
        var $this = this;
        var parent = templateNode.parentNode;

        API.getDataList(this.def.action, this.def.params, function (data) {
            if (typeof template === "function") {
                if (mock) {
                    data = mock;
                }
                $this.def.prevPage = $this.def.currentPage || 1;
                $this.def.currentPage = data.currentPage || 1;
                $this.def.totalPage = data.totalPage || 1;
                if (data.datas.length !== 0) {
                    parent.innerHTML += template($this.def.tempId, data.datas);
                    //缓存item节点
                    $this.nodeCache = parent.getElementsByClassName($this.def.itemClassName);
                    $this.initFocus()
                }
                var pageControl = document.getElementById($this.def.pageControlId);
                if ($this.def.pageControl) {
                    pageControl.getElementsByClassName('page-info')[0].innerHTML = '<span>' + $this.def.currentPage + '/' + $this.def.totalPage + '</span>';
                } else {
                    if (pageControl)
                        pageControl.innerHTML = '';
                }
                $this.def.callback(data)
            } else {
                console.error('请先引入art-template')
            }
        });
        console.log('获取数据');
        return this;
    };
    //初始化焦点
    List.prototype.getNodeCache = function () {
        if (JSON.stringify(this.nodeCache) === '{}') {
            this.nodeCache = document.getElementsByClassName(this.def.itemClassName)
        }
        return this.nodeCache;
    };
    List.prototype.initFocus = function () {
        var column = this.def.col;
        //STEP1：根据ClassName生成IDName
        //添加IDName
        if (this.def.idPrefix) {
            this.def.fullIdPrefix = (this.def.idPrefix + '-' + this.def.itemClassName).toCamelCase();
        } else {
            this.def.fullIdPrefix = this.def.itemClassName.toCamelCase();
        }

        for (var i = 0; i < this.nodeCache.length; i++) {
            this.nodeCache[i].id = this.def.fullIdPrefix + (i + 1);
        }

        //初始化元素位置
        if (this.def.positionControl) {
            this.initPosition();
        }
        //生成焦点控制

        for (var i = 0; i < this.nodeCache.length; i++) {

            _global[this.nodeCache[i].id + '_json'] = {};
            _global[this.nodeCache[i].id + '_json'].go_left = this.nodeCache[i - 1] ? this.nodeCache[i - 1].id : '';
            _global[this.nodeCache[i].id + '_json'].go_top = this.nodeCache[i - column] ? this.nodeCache[i - column].id : '';
            _global[this.nodeCache[i].id + '_json'].go_right = this.nodeCache[i + 1] ? this.nodeCache[i + 1].id : '';
            _global[this.nodeCache[i].id + '_json'].go_bottom = this.nodeCache[i + column] ? this.nodeCache[i + column].id : '';
            //处理竖直排列只有一列时左右不进行移动
            if (column === 1 && this.def.direction === 'vertical') {
                _global[this.nodeCache[i].id + '_json'].go_left = '';
                _global[this.nodeCache[i].id + '_json'].go_right = '';
            }

            _global[this.nodeCache[i].id + '_onfocus'] = setFocus;
            _global[this.nodeCache[i].id + '_onblur'] = setBlur;
            _global[this.nodeCache[i].id + '_onsubmit'] = function (code, id) {
                // tools.removeClass(id, 'active');
            };
        }
        //STEP2：添加焦点事件
        //此处处理翻页按钮向上焦点问题
        if (this.def.pageControl) {
            _global.prevBtn_json.go_top = this.nodeCache[this.nodeCache.length - 1].id;
            _global.nextBtn_json.go_top = this.nodeCache[this.nodeCache.length - 1].id;
            //处理焦点在翻页按钮时，列表第一项为active
            if (_global.keyopt.options.focusElm === 'prevBtn' || _global.keyopt.options.focusElm === 'nextBtn') {
                tools.removeClass(this.nodeCache[0].id, 'active');
            }
            //设置列表向下焦点到下一页按钮
            this.setListGoBottom('nextBtn');
        }
        if (this.def.keyPressControl) {
            this.initKeyPressControl();
        }
        //STEP3：设置特殊焦点事件
        if (this.def.direction === 'horizontal') {

        } else {

        }
        return this;
    };
    List.prototype.setListGoLeft = function (idName) {
        return this.setListGo('left', idName)
    };
    List.prototype.setListGoTop = function (idName) {
        return this.setListGo('top', idName)
    };
    List.prototype.setListGoBottom = function (idName) {
        return this.setListGo('bottom', idName)
    };
    List.prototype.setListGoRight = function (idName) {
        return this.setListGo('right', idName)
    };
    List.prototype.setListGo = function (position, idName) {
        var column = this.def.col;
        for (var i = 0; i < this.nodeCache.length; i++) {
            switch (position) {
                case 'left':
                    if ((i + 1) % column === 1 || column === 1) {
                        _global[this.nodeCache[i].id + '_json']['go_' + position] = idName;
                    }
                    break;
                case 'top':
                    if (i < column) {
                        _global[this.nodeCache[i].id + '_json']['go_' + position] = idName;
                    }
                    break;
                case 'bottom':
                    if (this.nodeCache.length - i <= column) {
                        _global[this.nodeCache[i].id + '_json']['go_' + position] = idName;
                    }
                    break;
                case 'right':
                    if ((i + 1) % column === 0 || column === 1) {
                        _global[this.nodeCache[i].id + '_json']['go_' + position] = idName;
                    }
                    break;
            }
        }
        return this;
    };
    List.prototype.setListOnSubmit = function (callback) {
        for (var i = 0; i < this.nodeCache.length; i++) {
            _global[this.nodeCache[i].id + '_onsubmit'] = callback;
        }
    };
    List.prototype.setListOnFocus = function (callback) {
        for (var i = 0; i < this.nodeCache.length; i++) {
            _global[this.nodeCache[i].id + '_onfocus'] = function (code, id) {
                setFocus(code, id);
                callback(code, id);
            };
        }
    };
    List.prototype.setListOnBlur = function (callback) {
        for (var i = 0; i < this.nodeCache.length; i++) {
            _global[this.nodeCache[i].id + '_onblur'] = function (code, id) {
                setBlur(code, id);
                callback(code, id);
            };
        }
    };
    //添加翻页控件
    List.prototype.addPageControl = function (left, top, id) {
        this.def.pageControl = true;
        var $this = this;
        console.log('添加翻页控制');
        if (id) {
            this.def.pageControlId = id
        }
        var pageControl = document.getElementById(this.def.pageControlId);
        left && (this.def.pageControlLeft = left) && (pageControl.style.left = this.def.pageControlLeft);
        top && (this.def.pageControlTop = top) && (pageControl.style.top = this.def.pageControlTop);

        var html =
            '<div id="prevBtn" class="prev-container">' +
            '<span class="prev-btn">上一页</span>' +
            '</div>' +
            '<div class="page-info">' +
            '<span>1/1</span>' +
            '</div>' +
            '<div id="nextBtn" class="next-container">' +
            '<span class="next-btn">下一页</span>' +
            '</div>';
        pageControl.className = 'page-control';
        pageControl.innerHTML = html;
        _global.prevBtn_json = {
            "go_left": "",
            "go_top": "",
            "go_right": "nextBtn",
            "go_bottom": ""
        };
        _global.prevBtn_onfocus = function (code, id) {
            tools.addClass(id, 'active');
        };
        _global.prevBtn_onblur = function (code, id) {
            tools.removeClass(id, 'active');
        };
        _global.prevBtn_onsubmit = function (code, id) {
            $this.prevPage()
        };
        _global.nextBtn_json = {
            "go_left": "prevBtn",
            "go_top": "",
            "go_right": "",
            "go_bottom": ""
        };
        _global.nextBtn_onfocus = function (code, id) {
            tools.addClass(id, 'active');
        };
        _global.nextBtn_onblur = function (code, id) {
            tools.removeClass(id, 'active');
        };
        _global.nextBtn_onsubmit = function (code, id) {
            $this.nextPage()
        };
        return this;
    };
    List.prototype.addKeyPressControl = function (key) {
        this.def.keyPressControl = true;
        if (key) {
            this.def.keyPress = 'UPDOWN'
        }
        return this;
    };
    List.prototype.initKeyPressControl = function () {
        if (this.firstView) {
            //解决第一次访问默认焦点问题
            keyopt.moveToElm(this.nodeCache.length && this.nodeCache[0].id);
            this.firstView=false;
        }
        var _this = this;
        var column = this.def.col;

        console.log(this.def.fullIdPrefix);

        for (var i = 0; i < this.nodeCache.length; i++) {
            if (this.def.keyPress) {
                //上
                if (i < column) {
                    _global[this.nodeCache[i].id + '_onblur'] = function (code, id) {
                        if (code === 'go_top') {
                            _this.prevPage();
                        }
                        _this.def.lastElemIndex = parseInt(id.replace(/[^0-9]/ig, ""));
                        _this.def.lastDirection = code;
                        console.log(_this.def.lastElemIndex, _this.def.lastDirection);
                        setBlur(code, id);
                    }
                }
                //下
                if (this.def.params.pageSize - i <= column) {
                    _global[this.nodeCache[i].id + '_onblur'] = function (code, id) {
                        if (code === 'go_bottom') {
                            _this.nextPage();
                        }
                        _this.def.lastElemIndex = parseInt(id.replace(/[^0-9]/ig, ""));
                        _this.def.lastDirection = code;
                        console.log(_this.def.lastElemIndex, _this.def.lastDirection);
                        setBlur(code, id);
                    }
                }
            } else {
                //左
                if ((i + 1) % column === 1) {
                    _global[this.nodeCache[i].id + '_onblur'] = function (code, id) {
                        if (code === 'go_left') {
                            _this.prevPage();
                        }
                        _this.def.lastElemIndex = parseInt(id.replace(/[^0-9]/ig, ""));
                        _this.def.lastDirection = code;
                        console.log(_this.def.lastElemIndex, _this.def.lastDirection);
                        setBlur(code, id);
                    }
                }
                //右
                if ((i + 1) % column === 0) {
                    _global[this.nodeCache[i].id + '_onblur'] = function (code, id) {
                        if (code === 'go_right') {
                            _this.nextPage();
                        }
                        _this.def.lastElemIndex = id.replace(/[^0-9]/ig, "");
                        _this.def.lastDirection = code;
                        console.log(_this.def.lastElemIndex, _this.def.lastDirection);
                        setBlur(code, id);
                    }
                }
                if (column === 1) {
                    _global[this.nodeCache[i].id + '_onblur'] = function (code, id) {
                        if (code === 'go_left') {
                            _this.prevPage();
                        }
                        if (code === 'go_right') {
                            _this.nextPage();
                        }
                        _this.def.lastElemIndex = id.replace(/[^0-9]/ig, "");
                        _this.def.lastDirection = code;
                        console.log(_this.def.lastElemIndex, _this.def.lastDirection);
                        setBlur(code, id);
                    }
                }
            }
        }
        if (this.def.lastElemIndex) {
            var curElemId = this.def.fullIdPrefix + '1';
            var curElemIdIndex = 1;
            if (this.def.keyPress) {
                switch (this.def.lastDirection) {
                    case 'go_top':
                        curElemIdIndex = _this.def.lastElemIndex + column;
                        if(column===1){
                            curElemIdIndex=this.nodeCache.length;
                        }
                        curElemId = this.findAbleFocusElemId(curElemIdIndex);
                        keyopt.options.focusElm = curElemId;
                        tools.addClass(curElemId, 'active');
                        break;
                    case 'go_bottom':
                        curElemIdIndex = _this.def.lastElemIndex - column;
                        if(column===1){
                            curElemIdIndex=1
                        }
                        curElemId = this.findAbleFocusElemId(curElemIdIndex);
                        keyopt.options.focusElm = curElemId;
                        tools.addClass(curElemId, 'active');
                        break;
                    default:
                        break;
                }

            } else {
                switch (this.def.lastDirection) {
                    case 'go_left':
                        curElemIdIndex = _this.def.lastElemIndex + (column - 1);
                        curElemId = this.findAbleFocusElemId(curElemIdIndex);
                        keyopt.options.focusElm = curElemId;
                        tools.addClass(curElemId, 'active');
                        break;
                    case 'go_right':
                        curElemIdIndex = _this.def.lastElemIndex - (column - 1);
                        curElemId = this.findAbleFocusElemId(curElemIdIndex);
                        keyopt.options.focusElm = curElemId;
                        tools.addClass(curElemId, 'active');
                        break;
                    default:
                        break;
                }

            }
        }
    };

    List.prototype.findAbleFocusElemId = function (curElemIdIndex) {
        while (true) {
            if (curElemIdIndex > this.nodeCache.length) {
                curElemIdIndex = curElemIdIndex - this.def.col;
                if (curElemIdIndex < this.def.col) {
                    curElemIdIndex = 1;
                    break;
                }
            } else {
                if (curElemIdIndex < 1) {
                    curElemIdIndex = 1
                }
                break;
            }
        }
        return this.def.fullIdPrefix + curElemIdIndex;
    };
    //获取配置信息
    List.prototype.getOptions = function () {
        return this.def;
    };
    //上一页
    List.prototype.prevPage = function () {
        if (this.def.params.pageIndex > 0) {
            this.def.params.pageIndex--;
        }
        if (this.def.currentPage !== 1)
            this.getData()
    };
    //下一页
    List.prototype.nextPage = function () {
        if (this.def.params.pageIndex < this.def.totalPage - 1) {
            this.def.params.pageIndex++;
        }
        if (this.def.totalPage !== this.def.currentPage)
            this.getData()
    };
    //清除列表数据
    List.prototype.clearData = function () {
        var templateNode = document.getElementById(this.def.tempId);
        var parent = templateNode.parentNode;
        var childs = parent.children;
        var newChilds = [];
        for (var i = 0; i < childs.length; i++) {
            if (childs[i].id !== this.def.tempId) {
                newChilds.push(childs[i])
            }
        }
        for (var i = 0; i < newChilds.length; i++) {
            parent.removeChild(newChilds[i])
        }
    };
    List.prototype.clear = function () {
        this.clearData();
        document.getElementById(this.def.pageControlId).innerHTML = '';
    };
    //item自动定位
    List.prototype.initPosition = function () {
        if (0 === this.nodeCache.length) {
            return
        }
        //绝对定位
        //每个元素宽高
        var height = this.def.itemHeight || this.nodeCache[0].offsetHeight,
            width = this.def.itemWidth || this.nodeCache[0].offsetWidth;
        //每个元素偏移间隔
        var offsetTop = this.def.offsetTop, offsetLeft = this.def.offsetLeft;
        //总行数，总列数
        var colNum = this.def.col;
        var curRow, curCol;
        for (var i = 0; i < this.nodeCache.length; i++) {
            curRow = Math.floor(i / colNum);
            curCol = i % colNum;
            this.nodeCache[i].style.top = (height + offsetTop) * curRow + 'px';
            this.nodeCache[i].style.left = (width + offsetLeft) * curCol + 'px';
        }
    };
    List.prototype.addPositionControl = function (height, width, offsetTop, offsetLeft) {
        this.def.itemHeight = height;
        this.def.itemWidth = width;
        this.def.offsetTop = offsetTop;
        this.def.offsetLeft = offsetLeft;
        this.def.positionControl = true;
        return this;
    };

    function extend(target, options, deep) {
        for (var key in options) {
            if (options.hasOwnProperty(key)) {
                var copy = options[key];
                if (deep && copy instanceof Array) {
                    target[key] = extend(target[key], copy, deep);
                } else if (deep && copy instanceof Object) {
                    target[key] = extend(target[key], copy, deep);
                } else {
                    target[key] = options[key];
                }
            }
        }
        return target;
    }

    function setBlur(code, id) {
        if (document.getElementById(id)) {
            tools.removeClass(id, 'active');
            var marquee = document.getElementById(id).getElementsByClassName('marquee');
            for (var i = 0; i < marquee.length; i++) {
                marquee[i].innerHTML = marquee[i]
                    .innerHTML.replace('<marquee>', "")
                    .replace("</marquee>", "");
            }
        }
    }

    function setFocus(code, id) {
        if (document.getElementById(id)) {
            tools.addClass(id, 'active');
            var marquee = document.getElementById(id).getElementsByClassName('marquee');
            for (var i = 0; i < marquee.length; i++) {
                if (marquee[i].scrollWidth > marquee[i].offsetWidth) {
                    marquee[i].innerHTML = "<marquee>" + marquee[i].innerHTML + "</marquee>";
                }
            }
        }
    }

    //转驼峰命名法
    String.prototype.toCamelCase = function () {
        var re = /-(\w)/g;
        return this.replace(re, function ($0, $1) {
            return $1.toUpperCase();
        });
    };

    _global = (function () {
        return this || (0, eval)('this');
    }());
    if (typeof module !== "undefined" && module.exports) {
        module.exports = List;
    } else if (typeof define === "function" && define.amd) {
        define(function () {
            return List;
        });
    } else {
        !('List' in _global) && (_global.List = List);
    }
})();